package com.huan.iteye.job;

import com.huan.iteye.analysis.support.BlogAnalysisSupport;
import com.huan.iteye.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.internet.MimeMessage;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 博客分析结果邮件通知
 *
 * @author huan.fu
 * @date 2018/9/18 - 13:41
 */
@Slf4j
@Component
public class BlogAnalysisResultEmailNotifyJob extends AbstractCustomJob {

	/**
	 * 时间格式
	 */
	public static final String TIME_FORMAT = "yyyy-MM-dd";
	/**
	 * 时间间隔7天
	 */
	public static final long DATE_RANGE = 7L;


	@Autowired
	private List<BlogAnalysisSupport> blogAnalysisSupports;
	@Autowired
	private JavaMailSender javaMailSender;
	@Value("${iteye.mail.from}")
	public String mailFrom;
	@Value("${iteye.mail.to}")
	public String mailTo;

	@Override
	public void doExecute(String workDate) {
		LocalDate startDate = LocalDate.parse(workDate, DateTimeFormatter.ofPattern(TIME_FORMAT)).minusDays(1L);
		LocalDate endDate = startDate.minusDays(DATE_RANGE);
		List<String> rangeDates = DateUtil.calculateDateRange(endDate, startDate);

		StringBuilder builder = new StringBuilder(1000);
		wrapCss(builder);
		blogAnalysisSupports.forEach(support -> builder.append(support.analysis(rangeDates)));

		MimeMessage mimeMessage = javaMailSender.createMimeMessage();
		try {
			MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
			helper.setFrom(mailFrom);
			helper.setTo(mailTo);
			helper.setSubject("iteye-blog-分析统计");
			StringBuilder html = new StringBuilder();
			html.append("<h2>博客分析统计:</h2>");
			html.append(builder.toString());
			html.append("<hr/>");
			helper.setText(html.toString(), true);
			javaMailSender.send(mimeMessage);
		} catch (Exception e) {
			log.error("邮件发送失败", e);
		}
	}

	/**
	 * 包装 css
	 *
	 * @param builder
	 */
	private void wrapCss(StringBuilder builder) {
		builder.append("<style type=\"text/css\">")
				.append("table { width: 100%;  padding: 0; margin: 0; }")
				.append("table thead th { font: bold 11px \"Trebuchet MS\", Verdana, Arial, Helvetica, sans-serif; color: #4f6b72; border-right: 1px solid #C1DAD7; border-bottom: 1px solid #C1DAD7; border-top: 1px solid #C1DAD7; letter-spacing: 2px; text-transform: uppercase; text-align: left; padding: 6px 6px 6px 12px; background: #CAE8EA  no-repeat; }")
				.append("table tbody td { border-right: 1px solid #C1DAD7; border-bottom: 1px solid #C1DAD7;  background: #fff; font-size:11px;  padding: 6px 6px 6px 12px; color: #4f6b72; }")
				.append("</style>");
	}
}
